<template>
    <el-dialog v-model="state.show" class="operate-dialog" :close-on-click-modal="false" width="700" destroy-on-close draggable @close="onClose">
        <template #header>
            <div class="title">个人密码修改</div>
        </template>
        <div class="auth-dialog">
            <el-form ref="formRef" :model="state.form" :rules="rules" style="width: 100%" label-width="120px">
                <el-form-item label="旧密钥" prop="old_password">
                    <el-input v-model="state.form.old_password" type="password" show-password />
                </el-form-item>
                <el-form-item label="新密码" prop="new_password">
                    <el-input v-model="state.form.new_password" type="password" show-password />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div style="width: 100%; text-align: center">
                <el-button type="danger" @click="onClose">取消</el-button>
                <el-button type="primary" @click="onSubmit">修改</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, FormItemRule } from 'element-plus';
import { buildValidatorData } from '@/utils/validate';
import api from '@/api';

interface ChangePasswordState {
    show: boolean;
    form: {
        old_password: string;
        new_password: string;
    };
}

const formRef = ref();
const state = reactive<ChangePasswordState>({
    show: false,
    form: {
        old_password: '',
        new_password: '',
    },
});

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    old_password: [buildValidatorData({ name: 'required', title: '旧密钥' })],
    password: [buildValidatorData({ name: 'required', title: '新密钥' })],
});

const onSubmit = () => {
    formRef.value?.validate().then((validate: any) => {
        if (validate) {
            api.post('/api/web/user/change-password', {
                old_password: state.form.old_password,
                new_password: state.form.new_password,
            })
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage.success('修改密码成功');
                        state.show = false;
                    }
                })
                .catch((error) => {
                    ElMessage.error(`code:${error.code} msg:${error.msg}`);
                });
        }
    });
};

const onClose = () => {
    state.show = false;
};

const open = () => {
    state.show = true;
};

defineExpose({
    open,
});
</script>

<style scoped lang="scss"></style>
